package lime.dql.view;

import java.util.ArrayList;
import java.util.List;

import lime.dql.provider.HistoryLabelProvider;
import lime.model.History;

import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.ui.part.ViewPart;

public class DqlHistoryView extends ViewPart {

	public static final String ID = "lime.dql.view.history";

	List<History> statements = new ArrayList<History>();
	
	// Widgets
	TableViewer historyViewer;
	
	@Override
	public void createPartControl(Composite parent) {

		historyViewer = new TableViewer(parent);
		historyViewer.getTable().setHeaderVisible(true);
		historyViewer.getTable().setLinesVisible(true);
		
		TableViewerColumn statementColumn = new TableViewerColumn(historyViewer, SWT.NONE);
		statementColumn.getColumn().setText("Statement");
		
		TableViewerColumn lastExecutedColumn = new TableViewerColumn(historyViewer, SWT.NONE);
		lastExecutedColumn.getColumn().setText("Last executed");
		
		historyViewer.setContentProvider(new ArrayContentProvider());
		historyViewer.setLabelProvider(new HistoryLabelProvider());
		historyViewer.setInput(statements);
		
		for (TableColumn column : historyViewer.getTable().getColumns()) {
			column.pack();
		}
		
		historyViewer.addDoubleClickListener(new IDoubleClickListener() {
			@Override
			public void doubleClick(DoubleClickEvent event) {
				ISelection selection = event.getSelection();
				if (selection != null && selection instanceof IStructuredSelection) {
					IStructuredSelection structuredSelection = (IStructuredSelection) selection;
					Object element = structuredSelection.getFirstElement();
					if (element instanceof History) {
						History history = (History) element;
						String statement = history.getStatement();
						DqlEditorView editorView = (DqlEditorView) getSite().getPage().findView(DqlEditorView.ID);
						editorView.setDql(statement);
					}
				}
			}
		});
	}

	@Override
	public void setFocus() {
		historyViewer.getTable().setFocus();
	}
	
	public void update(History history) {
		statements.add(0, history);
		historyViewer.setInput(statements);
		for (TableColumn column : historyViewer.getTable().getColumns()) {
			column.pack();
		}
		historyViewer.refresh();
	}

}
